<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>formData形式文件上传</title>
    <link rel="stylesheet" href="../public/css/bootstrap.min.css">
    <style type="text/css">
      .container {
        padding-top: 60px;
      }

      .padding {
        padding: 5px 0 20px 0;
      }
    </style>
  </head>

  <body>

    <div class="container">
      <div class="form-group">
        <label>请选择文件</label>
        <input type="file" id="upFile">
        <div class="progress">
          <div class="progress-bar" style="width: 30%;" id="bar">0%</div>
        </div>
      </div>
    </div>
  </body>
  <script></script>
  <script type="text/javascript">
    let upFile = document.querySelector("#upFile");
    // 1.当文件上传变化时触发这个事件
    upFile.onchange = function () {
      // 2.创建一个空的表单FormData
      let formData = new FormData();

      // 3.将用户选择的二进制文件追加到表单对象中
      formData.append('attrName', upFile.files[0]);
      // 4.发送ajax请求
      let xhr = new XMLHttpRequest();



      // 5.解决文件上传的进度问题
      // 文件上传过程中持续触发onprogress事件

      xhr.upload.onprogress = function (ev) {
        console.log(ev);
        // ev.loaded 文件已经上传了多少
        // ev.total  上传文件的总大小
        var result = (ev.loaded / ev.total) * 100 + '%';
        // 设置进度条的宽度
        bar.style.width = result;
        // 将百分比显示在进度条中
        bar.innerHTML = result;
      }


      xhr.open("post", "http://localhost:3000/upload");
      xhr.send(formData);
      xhr.onload = function () {
        if (xhr.status == 200) {
          console.log(xhr.responseText);
        }
      }
    }
  </script>

</html>